In computer programming, loop-invariant code consists of statements or expressions (in an imperativeprogramming language) which can be moved outside the body of a loop without affecting the semantics of the program. Loop-invariant code motion (also called hoisting or scalar promotion) is a compiler optimization which performs this movement automatically. ==Example== If we consider the following code sample, two optimizations can be easily applied.
The calculation x = y + z and x * x can be moved outside the loop since within they are loop invariant— they do not change over the iterations of the loop— so the optimized code will be something like this:
This code can be optimized further. For example, strength reduction could remove the two multiplications inside the loop (6 *i and a()), and induction variable elimination could then elide i completely. Since 6 * i must be in lock step with i itself, there is no need to have both.